import json

from fastapi import APIRouter

from business.base.AjaxJson import AjaxJson
from business.sys.menu import Menu
from utils.MySqlUtil import MySqlUtil

router = APIRouter(
    prefix="/init",
    tags=["init"],
    responses={404: {"description": "Not found"}},
)


@router.get("/init")
async def init():
    j = AjaxJson()
    try:
        db = MySqlUtil()
        sys_config = db.query('select * from sys_config sc where sc.status = %s', '1')
        init_dict = {}
        if len(sys_config) > 0:
            init_dict['homeInfo'] = {
                "title": sys_config[0]['home_title'],
                "href": sys_config[0]['home_page_href']
            }
            init_dict['logoInfo'] = {
                "title": sys_config[0]['sys_name'],
                'image': sys_config[0]['sys_logo'],
                'href': ''
            }
        menu_data_ = db.query('select * from sys_menu sm ', None)
        data_ = []
        for data in menu_data_:
            temp_ = {
                'id': data['id'],
                'parent_id': data['parent_id'],
                'title': data['menu_title'],
                'icon': data['menu_icon'],
                'href': '' if data['menu_href'] is None else data['menu_href'],
                'target': data['menu_target'],
            }
            data_.append(temp_)
        init_dict['menuInfo'] = Menu().build_menu_tree(data_)
        # j.data = json.dumps(init_dict, ensure_ascii=False)
        j.data = init_dict
        j.code = "success"
        j.msg = '初始化成功'
    except Exception as e:
        j.code = "failure"
        j.msg = '初始化失败'
        print(e)
    return j
